﻿using MQ.Core.Common;
using MQ.Core.Db;
using MQ.Core.Entity.System;
using MQ.Core.IRepository.System;
using MQ.Core.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MQ.Core.Repository.System
{
    public class DepartmentRepository: BaseRepository,IDepartmentRepository
    {
        private readonly ISqlDb db;
        private readonly MqDbContext context;

        public DepartmentRepository(ISqlDb db, MqDbContext context) : base(db)
        {
            this.db = db;
            this.context = context;
        }

        public override void Delete(string ids)
        {
            if (!ids.IsEmpty())
            {
                var list = new List<DepartmentEntity>(ids.Length);
                foreach(var item in ids.Split(','))
                {
                    list.Add(new DepartmentEntity() { Id = item.ToInt64() });
                }
                context.RemoveRange(list);
                context.SaveChanges();
            }
        }

        public override Task DeleteAsync(string ids)
        {
            if (!ids.IsEmpty())
            {
                var list = new List<DepartmentEntity>(ids.Length);
                foreach (var item in ids.Split(','))
                {
                    list.Add(new DepartmentEntity() { Id = item.ToInt64() });
                }
                context.RemoveRange(list);
                return context.SaveChangesAsync();
            }
            return Task.CompletedTask;
        }

        public override IEnumerable<T> GetList<T>(string query)
        {
            var json = query.ToJObject();
            var q = context.Department.AsEnumerable();
            if (!json["name"].IsEmpty())
            {
                q = q.Where(m => m.Name.Contains(json["name"].ToString()));
            }
            if (!json["companyId"].IsEmpty())
            {
                q = q.Where(m => m.CompanyId==json["name"].ToInt64());
            }
            return (IEnumerable<T>)q.ToList();
        }

        public override Task<IEnumerable<T>> GetListAsync<T>(string query)
        {
            throw new NotImplementedException();
        }

        public override IEnumerable<T> GetPageList<T>(Pagination pagination, string query)
        {
            var json = query.ToJObject();
            var q = context.Department.AsQueryable();
            if (!json["name"].IsEmpty())
            {
                q = q.Where(m => m.Name.Contains(json["name"].ToString()));
            }
            if (!json["companyId"].IsEmpty())
            {
                q = q.Where(m => m.CompanyId == json["name"].ToInt64());
            }
            return (IEnumerable<T>)q.ToPageList(pagination);
        }

        public override Task<IEnumerable<T>> GetPageListAsync<T>(Pagination pagination, string query)
        {
            throw new NotImplementedException();
        }
    }
}
